import 'package:flutter/material.dart';
import '../serve/file_serve.dart';

/// 分类标签显示组件
class CategoryTagsWidget extends StatefulWidget {
  final String category;
  final FileServe fileServe;
  final int maxDisplayTags;
  final VoidCallback? onTagTap;

  const CategoryTagsWidget({
    Key? key,
    required this.category,
    required this.fileServe,
    this.maxDisplayTags = 3,
    this.onTagTap,
  }) : super(key: key);

  @override
  _CategoryTagsWidgetState createState() => _CategoryTagsWidgetState();
}

class _CategoryTagsWidgetState extends State<CategoryTagsWidget> {
  List<Map<String, dynamic>> _topTags = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadTopTags();
  }

  @override
  void didUpdateWidget(CategoryTagsWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果分类发生变化，重新加载标签
    if (oldWidget.category != widget.category) {
      _loadTopTags();
    }
  }

  /// 公共刷新方法，供外部调用
  void refresh() {
    _loadTopTags();
  }

  Future<void> _loadTopTags() async {
    try {
      final topTags = await widget.fileServe.getCategoryTopTags(
        widget.category, 
        limit: widget.maxDisplayTags
      );
      
      if (mounted) {
        setState(() {
          _topTags = topTags;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('CategoryTagsWidget: 加载标签失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _showAllTags() {
    showDialog(
      context: context,
      builder: (context) => CategoryAllTagsDialog(
        category: widget.category,
        fileServe: widget.fileServe,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Container(
        height: 24,
        child: Row(
          children: [
            SizedBox(
              width: 12,
              height: 12,
              child: CircularProgressIndicator(strokeWidth: 1.5),
            ),
            SizedBox(width: 8),
            Text('加载标签中...', style: TextStyle(fontSize: 10, color: Colors.grey)),
          ],
        ),
      );
    }

    if (_topTags.isEmpty) {
      return Container(
        height: 24,
        child: Text(
          '暂无标签',
          style: TextStyle(fontSize: 10, color: Colors.grey[400]),
        ),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Wrap(
          spacing: 4,
          runSpacing: 2,
          children: [
              // 显示热门标签
              ..._topTags.map((tagData) => _buildTagChip(
                tagData['tag'] as String,
                tagData['count'] as int,
              )).toList(),
              
              // 显示"更多"按钮
              if (_topTags.length >= widget.maxDisplayTags)
                GestureDetector(
                  onTap: _showAllTags,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.grey[300]!, width: 0.5),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text(
                          '更多',
                          style: TextStyle(
                            fontSize: 9,
                            color: Colors.grey[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        SizedBox(width: 2),
                        Icon(
                          Icons.arrow_forward_ios,
                          size: 8,
                          color: Colors.grey[600],
                        ),
                      ],
                    ),
                  ),
                ),
          ],
        ),
      ],
    );
  }

  Widget _buildTagChip(String tag, int count) {
    return GestureDetector(
      onTap: widget.onTagTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
        decoration: BoxDecoration(
          color: Colors.blue[50],
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.blue[200]!, width: 0.5),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              tag,
              style: TextStyle(
                fontSize: 9,
                color: Colors.blue[700],
                fontWeight: FontWeight.w500,
              ),
            ),
            if (count > 1) ...[
              SizedBox(width: 2),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                decoration: BoxDecoration(
                  color: Colors.blue[100],
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  '$count',
                  style: TextStyle(
                    fontSize: 7,
                    color: Colors.blue[800],
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 显示分类所有标签的对话框
class CategoryAllTagsDialog extends StatefulWidget {
  final String category;
  final FileServe fileServe;

  const CategoryAllTagsDialog({
    Key? key,
    required this.category,
    required this.fileServe,
  }) : super(key: key);

  @override
  _CategoryAllTagsDialogState createState() => _CategoryAllTagsDialogState();
}

class _CategoryAllTagsDialogState extends State<CategoryAllTagsDialog> {
  List<Map<String, dynamic>> _allTags = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadAllTags();
  }

  Future<void> _loadAllTags() async {
    try {
      final allTags = await widget.fileServe.getCategoryAllTags(widget.category);
      
      if (mounted) {
        setState(() {
          _allTags = allTags;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('CategoryAllTagsDialog: 加载所有标签失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _viewDocumentsByTag(String tag) {
    Navigator.pop(context);
    // 可以导航到显示该标签下所有文档的页面
    _showDocumentsByTagDialog(tag);
  }

  void _showDocumentsByTagDialog(String tag) {
    showDialog(
      context: context,
      builder: (context) => DocumentsByTagDialog(
        category: widget.category,
        tag: tag,
        fileServe: widget.fileServe,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          Icon(Icons.label, color: Colors.blue, size: 20),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              '${widget.category} - 所有标签',
              style: TextStyle(fontSize: 16),
            ),
          ),
        ],
      ),
      content: Container(
        width: double.maxFinite,
        height: 400,
        child: _isLoading
            ? Center(child: CircularProgressIndicator())
            : _allTags.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.label_off, size: 48, color: Colors.grey),
                        SizedBox(height: 16),
                        Text('该分类暂无标签', style: TextStyle(color: Colors.grey)),
                      ],
                    ),
                  )
                : ListView.separated(
                    itemCount: _allTags.length,
                    separatorBuilder: (context, index) => Divider(height: 1),
                    itemBuilder: (context, index) {
                      final tagData = _allTags[index];
                      final tag = tagData['tag'] as String;
                      final count = tagData['count'] as int;

                      return ListTile(
                        dense: true,
                        leading: Container(
                          width: 32,
                          height: 32,
                          decoration: BoxDecoration(
                            color: Colors.blue[100],
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Center(
                            child: Text(
                              '$count',
                              style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                color: Colors.blue[700],
                              ),
                            ),
                          ),
                        ),
                        title: Text(
                          tag,
                          style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
                        ),
                        subtitle: Text(
                          '$count个文档',
                          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                        ),
                        trailing: Icon(Icons.arrow_forward_ios, size: 16),
                        onTap: () => _viewDocumentsByTag(tag),
                      );
                    },
                  ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text('关闭'),
        ),
      ],
    );
  }
}

/// 显示特定标签下所有文档的对话框
class DocumentsByTagDialog extends StatefulWidget {
  final String category;
  final String tag;
  final FileServe fileServe;

  const DocumentsByTagDialog({
    Key? key,
    required this.category,
    required this.tag,
    required this.fileServe,
  }) : super(key: key);

  @override
  _DocumentsByTagDialogState createState() => _DocumentsByTagDialogState();
}

class _DocumentsByTagDialogState extends State<DocumentsByTagDialog> {
  List<Map<String, dynamic>> _documents = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadDocuments();
  }

  Future<void> _loadDocuments() async {
    try {
      final documents = await widget.fileServe.getDocumentsByTagInCategory(
        widget.category,
        widget.tag,
      );
      
      if (mounted) {
        setState(() {
          _documents = documents;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('DocumentsByTagDialog: 加载文档失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.blue[100],
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              widget.tag,
              style: TextStyle(fontSize: 12, color: Colors.blue[700]),
            ),
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              '相关文档',
              style: TextStyle(fontSize: 16),
            ),
          ),
        ],
      ),
      content: Container(
        width: double.maxFinite,
        height: 300,
        child: _isLoading
            ? Center(child: CircularProgressIndicator())
            : _documents.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.description_outlined, size: 48, color: Colors.grey),
                        SizedBox(height: 16),
                        Text('暂无相关文档', style: TextStyle(color: Colors.grey)),
                      ],
                    ),
                  )
                : ListView.separated(
                    itemCount: _documents.length,
                    separatorBuilder: (context, index) => Divider(height: 1),
                    itemBuilder: (context, index) {
                      final doc = _documents[index];
                      final title = doc['title'] as String;
                      final time = doc['time'] as String?;

                      return ListTile(
                        dense: true,
                        leading: Icon(Icons.description, color: Colors.blue),
                        title: Text(
                          title,
                          style: TextStyle(fontSize: 14),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        subtitle: time != null
                            ? Text(
                                DateTime.parse(time).toString().substring(0, 16),
                                style: TextStyle(fontSize: 11, color: Colors.grey[600]),
                              )
                            : null,
                        onTap: () {
                          // 可以在这里添加打开文档的逻辑
                          Navigator.pop(context);
                        },
                      );
                    },
                  ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text('关闭'),
        ),
      ],
    );
  }
} 